package com.cksys.achievement.config;

import com.cksys.achievement.controller.VerifyCodeController;
import com.cksys.achievement.exception.ValidateCodeException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @ClassName: ValidateCodeFilter
 * @author: zyx
 * @E-mail: 1377631190@qq.com
 * @DATE: 2020/4/4 20:54
 */
@Component
public class ValidateCodeFilter extends OncePerRequestFilter {

    @Autowired
    AjaxAuthFailureHandler failureHandler;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException, IOException, ServletException {
        if(StringUtils.equals("/login", request.getRequestURI())
                && StringUtils.equalsIgnoreCase(request.getMethod(), "post")) {

            String requestCode = request.getParameter("verificationCode");
            try {
                // 1. 进行验证码的校验
                HttpSession session = request.getSession();
                String sessionCode = (String) session.getAttribute(VerifyCodeController.SESSION_KEY);

                if (null == sessionCode) {
                    throw new ValidateCodeException("验证码已失效！");
                }
                if (!sessionCode.equalsIgnoreCase(requestCode)) {
                    throw new ValidateCodeException("验证码错误！");
                }

                session.removeAttribute(VerifyCodeController.SESSION_KEY);
            } catch (ValidateCodeException e) {
                failureHandler.onAuthenticationFailure(request, httpServletResponse, e);
                return ;
            }
        }
        // 3. 校验通过，就放行
        filterChain.doFilter(request, httpServletResponse);
    }

}